/**
 * 将秒数转换为时间字符串
 * @param seconds {number} 传入的秒数
 * @param cFormat {string} 格式化字符串，默认为 "{h}:{i}:{s}"
 * @param hideZero {boolean} 是否隐藏 0 时和 0 分，默认为 false
 * @returns {string | null}
 * @example
 * formatTime(3661); // "01:01:01"
 * formatTime(3661, "{h}时{i}分{s}秒"); // "01时01分01秒"
 * formatTime(59, "{h}时{i}分{s}秒", true); // "59秒"
 */
export function formatTime(seconds: number, cFormat: string = "{h}:{i}:{s}", hideZero: boolean = false): string | null {
  if (seconds < 0 || isNaN(seconds)) {
    return null;
  }

  const formatObj: { [key: string]: number | string } = {
    h: Math.floor(seconds / 3600),
    i: Math.floor((seconds % 3600) / 60),
    s: seconds % 60
  };

  let formattedString = cFormat.replace(new RegExp("{([his])+}", "g"), (result, key) => {
    const value = formatObj[key];
    return value.toString().padStart(2, "0");
  });

  if (hideZero) {
    if (formatObj.h === 0) {
      formattedString = formattedString.replace(new RegExp("0{1,2}时"), "");
    }
    if (formatObj.i === 0) {
      formattedString = formattedString.replace(new RegExp("0{1,2}分"), "");
    }
  }

  return formattedString;
}

export default formatTime;
